package com.it.service;

import com.it.bean.Student;
import com.it.bean.User;
import com.it.mapper.StudentMapper;
import com.it.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class TestService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UserMapper userMapper;

    public List<Student> queryAll() {
        return studentMapper.selectAll();
    }

    public Student queryStudentById(String id) {
        return studentMapper.selectById(id);
    }

    @Transactional(rollbackOn = Exception.class)
    public Integer insertBatchStudent(boolean needException) {
        try {
            List<Student> list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                Student student = new Student();
                student.setName(String.valueOf(i));
                student.setGender(i % 2 == 0 ? "男" : "女");
                student.setMajor(i % 2 == 0 ? "python" : "java");
                student.setGrade(new Random().nextInt(100) + "");
                list.add(student);
            }
            Integer result = studentMapper.insertBatch(list);

            if (needException) {
                int error = 1 / 0;
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public User queryUserById(String id) {
        return userMapper.getUserById(id);
    }

}
